﻿using Rhino.Geometry;
using ArchiToolkit.Grasshopper;
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;

namespace CGAL.Grasshopper.Wrapper;

static class StraightSkeleton2D
{
    [ObjNames("StraightSkeleton2D", "SS2D", "Creates a 2D StraightSkeleton.")]
    [DocObj]
    public static Line[] Create(List<Point3d> OuterPointArray, List<Point3d> HolePointArray)
    {

        var OuterPointDoubleArray = new double[OuterPointArray.Count * 2];
        for (var i = 0; i < OuterPointArray.Count; i++)
        {
            OuterPointDoubleArray[i * 2] = OuterPointArray[i].X;
            OuterPointDoubleArray[i * 2 + 1] = OuterPointArray[i].Y;
        }

        var HolePointDoubleArray = new double[HolePointArray.Count * 2];
        for (var i = 0; i < HolePointArray.Count; i++)
        {
            HolePointDoubleArray[i * 2] = HolePointArray[i].X;
            HolePointDoubleArray[i * 2 + 1] = HolePointArray[i].Y;
        }

        var lineSizePtr = IntPtr.Zero;
        var linePtr = IntPtr.Zero;
        
        UnsafeNativeMethods.StraightSkeleton_Create(OuterPointDoubleArray, (ulong)OuterPointArray.Count, HolePointDoubleArray, (ulong)HolePointArray.Count, ref linePtr, ref lineSizePtr);
        var lineSize = Marshal.ReadInt32(lineSizePtr);
        var lines = new double[lineSize * 4];
        Marshal.Copy(linePtr, lines, 0, lineSize * 4);

        var result = new Line[lineSize];
        for (var i = 0; i < lineSize; i++)
        {
            result[i] = new Line(new Point3d(lines[i * 4], lines[i * 4 + 1], 0), new Point3d(lines[i * 4 + 2], lines[i * 4 + 3], 0));
        }
        UnsafeNativeMethods.ReleaseDoubleArray(linePtr);
        UnsafeNativeMethods.ReleaseInt(lineSizePtr);
        return result;

    }
}